<template>
    <!-- 质量整改通知单的操作页，包括：填报 0 ，调整 1 ，查看 2 -->
    <base-breadcrumb :title="$route.meta.title">
      <a-spin :spinning="loading">
        <a-card :bordered="false" class="base-info-style">
            <!-- 基本信息 -->
            <BaseInfo ref="BaseInfo" :form="form" :onlyRead="true" />
            <div v-if="onlyRead">
              <!-- 风险处理方案信息 -->
              <RiskTreatmentPlanInfo :form="form" :onlyRead="true" :showPlanBoardVisible="true" />
              <!-- 风险跟踪计划信息 -->
              <RiskTrackingPlanView :form="form" :api="api" :onlyRead="true" :showPlanBoardVisible="true" />
              <!-- 风险上报信息 -->
              <RiskReportingInfo :form="detailForm" :onlyRead="true" :showPlanBoardVisible="true" />
               <!-- 风险复核信息 -->
               <RiskReviewInfo :form="detailForm" :onlyRead="true" :showPlanBoardVisible="true" />
            </div>
             <div v-else>
              <!-- 风险上报信息 -->
              <RiskReportingInfo ref="RiskReportingInfo" :form="detailForm" :onlyRead="true" />
              <!-- 风险复核信息 -->
              <RiskReviewInfo ref="RiskReviewInfo" :form="detailForm" :onlyRead="true" />
              <!-- 风险处理方案信息 -->
              <RiskTreatmentPlanInfo ref="RiskTreatmentPlanInfo" :form="form"  />
              <!-- 风险跟踪计划信息 -->
              <RiskTrackingPlanInfo ref="RiskTrackingPlanInfo" :form="form"  />
             </div>
        </a-card>
        <!-- 页脚操作栏 -->
        <Footer
          :editModel="editModel"
          :loading="footerLoading"
          @submitDraft="submitDraft" 
          @submitFormal="submitFormal"
          v-if="!isFromAudit"
        />
      </a-spin>
      <div v-if="!isConsultation && isFromAudit" class="page-btn-right-top">
        <a-button
          v-check-visible-in-detail
          style="margin: 0 10px"
          @click="$close"
        >
          关闭
        </a-button>
      </div>
      <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
    </base-breadcrumb>
  </template>
  
  <script>
  import { riskReporting } from '@/api/quality/risk/riskReporting'
  import { riskTracking } from '@/api/quality/risk/riskTracking'
  import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
  import BaseInfo from '@/views/quality/riskIdentification/components/BaseInfo'
  import RiskTreatmentPlanInfo from '@/views/quality/riskIdentification/components/RiskTreatmentPlanInfo'
  import RiskTrackingPlanInfo from '@/views/quality/riskIdentification/components/RiskTrackingPlanInfo'
  import RiskTrackingPlanView from '@/views/quality/riskIdentification/components/RiskTrackingPlanView'
  import RiskReportingInfo from '@/views/quality/riskIdentification/components/RiskReportingInfo'
  import RiskReviewInfo from '@/views/quality/riskIdentification/components/RiskReviewInfo'
  import Footer from '@/views/quality/riskIdentification/components/Footer'
  
  export default {
    name: 'a' + Date.now(),
    extends: new BaseEditPage(),
    components: {
      BaseInfo,
      RiskTreatmentPlanInfo,
      RiskTrackingPlanInfo,
      RiskTrackingPlanView,
      RiskReportingInfo,
      RiskReviewInfo,
      Footer
    },
    props: {
      // 是否作为意见征询
      isConsultation: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        id: this.$route.query.id || '',
        historyId: this.$route.query.historyId || '',
        loading: false, // 请求加载框
        editModel: this.$route.query.editModel || '0', // 操作类型：0，1 编辑，2 查看, 3 更新
        form: {
          projectId:"",
          updateUserName: this.$userInfo().name,
          fillTime: this.$dateFormat(Date.now(), 'D'),
        },
        detailForm: {},
        footerLoading: { 'submitDraft': false, 'submitFormal': false, 'submitValidate': false },
        api: riskTracking, // 请求api
        titles: ['', '编辑', '查看', '更新'], // 根据操作类型自适应的标题
        projectId: this.$route.query.projectId || '',
        branchComName: this.$route.query.branchComName || '',
        projectName: this.$route.query.projectName || '',
        isFromAudit: false, // 是否来自审批
        //获取流程配置值
        processConfig: null,
        //点击提交发送流程配置值
        setProcessConfig: null,
        businessId: null
      }
    },
    async created() {
      this.$route.meta.title = [
        '',
        '质量风险跟踪编辑',
        '质量风险跟踪查看',
        '质量风险跟踪更新'
      ][this.editModel]
      this.isFromAudit = !!this.$route.query.businessId
      // 初始化
      this.init()
      //获取通过获取流程配置值
      this.processConfig = await this.$getConfigFn('quality_risk_monitor_plan')
    },
    computed: {
      // 只读模式
      onlyRead() {
        return this.editModel == 2 || this.isFromAudit
      }
    },
    methods: {
      /**
       * @description: 初始化
       */
      init() {
        // 当操作为新增和生成整改单,则自动获取下发人和下发时间，否则请求业务详情
        if (this.id) {
          this.loading = true
          this.api
            .getDetail(this.id, this.historyId || '-1')
            .then((res) => {
              if (res.data) {
                // 映射表单
                this.form = res.data
                if (res.data.branchComName && res.data.projectName) {
                  this.form.viewName = res.data.branchComName + '/' + res.data.projectName
                }
              }
              if (res.data.escalationId) {
                riskReporting
                .getDetail(res.data.escalationId)
                .then((res) => {
                  if (res.data) {
                    // 映射表单
                    res.data.projectTypeId = res.data.projectTypeId ? res.data.projectTypeId.toString(): ''
                    res.data.subProjectId = res.data.subProjectId ? res.data.subProjectId.toString(): ''
                    this.detailForm = res.data
                  }
                })
              }
            })
            .finally(() => {
              this.loading = false
            })
        } else {
          this.form.fillerName = this.$userInfo()?.name
          this.form.fillerId = this.$userInfo().id
          this.form.modifiedTime = this.$dateFormat(new Date(), 'D')
          this.form.viewName = this.branchComName + '/' + this.projectName
          this.form.projectId = this.projectId
        }
      },
      submitDraft() {
        try {
          const dataSource = this.$refs.RiskTrackingPlanInfo.dataSource || []
          this.submit('submitDraft', dataSource)
        } catch (e) {
          console.log(e)
        }
      },
      submitFormal() {
        try {
          const RiskTreatmentPlanInfo = this.$refs.RiskTreatmentPlanInfo
          RiskTreatmentPlanInfo.$refs?.ruleForm.validate(valid => {
          if (valid) {
            const columns1 = this.$refs.RiskTrackingPlanInfo.columns || []
            const columns = columns1.filter(v => v.dataIndex !== 'action').map(item => item.dataIndex)
            const dataSource = this.$refs.RiskTrackingPlanInfo.dataSource || []
            if (dataSource.length === 0) {
              this.$warning({
                title: '提示',
                content: '请添加风险跟踪计划信息',
                okText: '确定'
              })
              return false
            }
            const emtyArr = dataSource.filter((obj) => {
              let tag = false
              for (let key in obj) { 
                if (columns.indexOf(key) !== -1 && !obj[key]) {
                  tag = true
                  break;
                }
              }
              return tag;
            })
            if (emtyArr.length) {
              this.$warning({
                title: '提示',
                content: '请将风险跟踪计划信息填写完整再提交！',
                okText: '确定'
              })
              return false
            }
            const takeEffectDate = dataSource.filter(item => this.moment(item['takeEffectDate']).diff(this.moment(new Date()), 'days') < 0 && item.operation != false)
            if (takeEffectDate.length) {
              this.$warning({
                title: '提示',
                content: '生效日期不能小于今天',
                okText: '确定'
              })
              return false
            }
            if (this.processConfig == 4) {
              this.submit('submitFormal', dataSource)
            } else {
              this.$confirm({
                titile: '提示',
                content: '确认提交，提交后不可撤回？',
                onOk: () => {
                  return this.submit('submitFormal', dataSource)
                }
              })
            }
            
          }
        })
        } catch (e) {
          console.log(e)
        }
      },
      /**
       * @description: 提交表单
       * @param {*} status
       * @return {*}
       */
       submit(status, dataSource) {
        let name = '' // 根据操作切换url地址
        if (this.id) {
          if (this.editModel == '3') {
            name = 'adjustment'
          } else {
            name = 'updatePost'
          }
        } else {
          name = 'handleCreate'
        }
        this.setProcessConfig = null;
        this.submitApprovalConfirm(status =='submitFormal' ? this.processConfig : 6, (flag)=>{
          if(!flag) {
            this.footerLoading[status] = true
            return
          }
          const statusCode = {submitDraft: 0, submitFormal: 1}[status]
          const submitData = {
            status: statusCode,
            id: this.id,
            handleOpinion: this.form.handleOpinion,
            filesIds: this.form.fileInfos ? this.form.fileInfos.map(item => item.commonId) : [],
            details: dataSource
          }
          // 提交表单
          this.footerLoading[status] = true
          return this.api[name](submitData)
            .then((res) => {
              if (res.code === 200 || res.data.code === 200) {
                //提交时，返回id
                this.$message.success(['保存草稿', '提交'][statusCode] + '成功！')
                if (status =='submitFormal') {
                  this.businessId = res.data.id;
                  this.setProcessConfig = this.processConfig;
                  return
                }
                this.$multiTab.close()
              }
            })
            .finally(() => {
              this.footerLoading[status] = false
            })
        })
        
      },
    }
  }
  </script>